package com.malbbmsomanager.reports;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import com.malbbmsomanager.adapter.DM_BBM_Inquiry_Adapters;
import com.malbbmsomanager.adapter.DM_BBM_List_Adapters;
import com.malbbmsomanagerdemo.DM_BBM_InvoiceMenu;
import com.malbbmsomanagerdemo.R;

import android.app.ActionBar;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.graphics.Color;
import android.os.AsyncTask;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.view.animation.Animation.AnimationListener;
import android.widget.AdapterView;
import android.widget.CalendarView;
import android.widget.EditText;
import android.widget.FilterQueryProvider;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RatingBar;
import android.widget.SimpleCursorAdapter;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.RatingBar.OnRatingBarChangeListener;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;
import android.widget.Toast;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;

public class DM_BBM_Items_Inquiry extends Activity implements
		ActionBar.OnNavigationListener, AnimationListener {

	private static final String TAG = null;
	// Database Name.

	String item_result_1 = "0", item_result_2 = "0", item_result_3 = "0",
			item_result_4 = "0", item_result_5 = "0", item_result_6 = "0",
			item_result_7 = "0", item_result_8 = "0", item_result_9 = "0",
			item_result_13 = "0", item_result_10, PrintGrandTot;

	int item_result_tot_2 = 0, item_result_tot_3 = 0, item_result_tot_4 = 0,
			item_result_tot_5 = 0, item_result_tot_6 = 0,
			item_result_tot_7 = 0, item_result_tot_8 = 0,
			item_result_tot_9 = 0, PrintGrandTot_tot = 0;

	private ActionBar actionBar;
	ImageView imgLogo;
	Animation animRotate;
	LinearLayout DisplayResults;
	EditText myFilterCustomer;
	Button eadingrecord_2;
	// private DM_BBM_Inquiry_Adapters dbHelperCustomer;
	private SQLiteDatabase mydb;
	private static final String DATABASE_NAME = "dminvoicemanagerbbm.db";
	private String ITEMS_INQUIRY = "Items_Inquiry";

	private DM_BBM_Inquiry_Adapters dbHelperInquiryReport;
	private SimpleCursorAdapter dataAdapterItemInquiry;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.dm_bbm_items_inquiry);

		actionBar = getActionBar();
		// Hide the action bar title
		actionBar.setDisplayShowTitleEnabled(true);
		actionBar.setDisplayHomeAsUpEnabled(false);

		mydb = openOrCreateDatabase(DATABASE_NAME, Context.MODE_PRIVATE, null);
		mydb.execSQL("DROP TABLE IF EXISTS FPRecHed");
		mydb.execSQL("create table if not exists "
				+ ITEMS_INQUIRY
				+ "(_id integer primary key autoincrement,ItemCode text not null,TypeName  text not null,ItemName text not null,PurDesc text not null,BrandName text not null,Packing  text not null,FinalQty text not null,ResvQTY  text not null,STDPrice  text not null,USDPrice  text not null,UnDispQTY  text not null,PackSize  text not null,TAXCode  text not null,IQSummary text not null);");
		mydb.close();

		myFilterCustomer = (EditText) findViewById(R.id.eadingrecord_1);
		DisplayResults = (LinearLayout) findViewById(R.id.iteminquirymain);
		imgLogo = (ImageView) findViewById(R.id.animateimage);
		eadingrecord_2 = (Button) findViewById(R.id.eadingrecord_2); 
		
		eadingrecord_2.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				myFilterCustomer.setText("");
			}
		});
		
		
		// load the animation
		animRotate = AnimationUtils.loadAnimation(getApplicationContext(),
				R.anim.rotate);
		imgLogo.setVisibility(View.VISIBLE);
		// set animation listener
		animRotate.setAnimationListener(this);
		// start the animation
		imgLogo.startAnimation(animRotate);

		dbHelperInquiryReport = new DM_BBM_Inquiry_Adapters(this);
		dbHelperInquiryReport.open();

		new ProcessingReport().execute();
	}

	private class ProcessingReport extends AsyncTask<Void, Void, Void> {
		private final String TAG = null;

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
		}

		@Override
		protected Void doInBackground(Void... arg0) {
			// TODO Auto-generated method stub
			mydb = openOrCreateDatabase(DATABASE_NAME, Context.MODE_PRIVATE,
					null);

			/********* SELECT QUIRIES **********/
			/********* READ ITEM MASTER **********/
			Cursor selectItems = null;
			Cursor selectItemsType = null;
			Cursor selectItemsBrand = null;
			Cursor selectItemsFreeQty = null;
			Cursor selectItemsfStkResvDet = null;
			Cursor selectItemsPrice = null;
			Cursor selectItemsPricefDailyCur = null;

			String queryItems, queryItemsType, queryItemsBrand, queryItemsFreeQty, queryItemsfStkResvDet, queryItemsPrice, queryItemsfDailyCur;

			// fItemFreeQty
			queryItems = "SELECT FI.ItemCode ,FI.TypeCode ,FI.ItemName ,FI.PurDesc ,FI.BrandCode ,FI.packing ,FI.PrilCode ,FI.PackSize ,FI.TaxComCode FROM FItems FI GROUP BY FI.ItemCode";
			selectItems = mydb.rawQuery(queryItems, null);

			if (selectItems != null) {
				if (selectItems.getCount() > 0) {
					while (selectItems.moveToNext()) {

						Log.v(TAG, "###########************###########");

						String Print_ItemCode = selectItems.getString(0);
						String Print_TypeCode = selectItems.getString(1);
						String Print_ItemName = selectItems.getString(2);
						String Print_PurDesc = selectItems.getString(3);
						String Print_BrandCode = selectItems.getString(4);
						String Print_packing = selectItems.getString(5);
						String Print_PrilCode = selectItems.getString(6);
						String Print_PackSize = selectItems.getString(7);
						String Print_TaxComCode = selectItems.getString(8);
						BigDecimal ItemPriceValue = new BigDecimal("0.00");
						BigDecimal ItemCurRate = new BigDecimal("0.00");
						BigDecimal RationPriceCurRate = new BigDecimal("0.00");

						String Print_TypeName = " ", Print_BrandName = " ", Print_FreeQty = "0.00", Print_ResvQty = "0.00", Print_ItemPrice = "0.00", Print_CurRate = "0.00";

						Log.v(TAG, "Print_ItemCode :" + "" + Print_ItemCode);
						/* Select Item Type Name (***TypeName***) */
						queryItemsType = "SELECT IT.TypeCode,IT.TypeName FROM ftype IT WHERE IT.TypeCode = '"
								+ Print_TypeCode + "'";
						selectItemsType = mydb.rawQuery(queryItemsType, null);
						if (selectItemsType != null) {
							if (selectItemsType.getCount() > 0) {
								while (selectItemsType.moveToNext()) {
									Print_TypeName = selectItemsType
											.getString(1);
									Log.v(TAG, "Print_TypeName :" + ""
											+ Print_TypeName);

								}
								selectItemsType.close();
							} else {
								Print_TypeName = " ";
							}
						}

						/* Select Item Brand Name(***BrandName***) */
						queryItemsBrand = "SELECT FB.BrandCode,FB.BrandName FROM FBrand FB WHERE FB.BrandCode = '"
								+ Print_BrandCode + "'";
						selectItemsBrand = mydb.rawQuery(queryItemsBrand, null);
						if (selectItemsBrand != null) {
							if (selectItemsBrand.getCount() > 0) {
								while (selectItemsBrand.moveToNext()) {
									Print_BrandName = selectItemsBrand
											.getString(1);
									Log.v(TAG, "Print_BrandName :" + ""
											+ Print_BrandName);

								}
								selectItemsBrand.close();
							} else {
								Print_BrandName = " ";
							}
						}

						/* Select Free Items Quantities */
						queryItemsFreeQty = "SELECT FQ.ItemCode,FQ.FreeQty FROM fItemFreeQty FQ WHERE FQ.ItemCode = '"
								+ Print_ItemCode + "'";
						selectItemsFreeQty = mydb.rawQuery(queryItemsFreeQty,
								null);
						try {
							if (selectItemsFreeQty != null) {
								if (selectItemsFreeQty.getCount() > 0) {
									while (selectItemsFreeQty.moveToNext()) {
										Print_FreeQty = selectItemsFreeQty
												.getString(1);
										Log.v(TAG, "Print_FreeQty :" + ""
												+ Print_FreeQty);

									}
									selectItemsFreeQty.close();
								} else {
									Print_FreeQty = "0.00";
								}
							}
						} catch (Exception e) {
							Log.v(TAG, "Print_FreeQty Exception:" + "" + e);
						}

						/* Select Free Items Fstkresvdet */
						queryItemsfStkResvDet = "SELECT FSK.Itemcode,sum(FSK.BalQty) as ResvQty FROM Fstkresvdet FSK WHERE FSK.ItemCode = '"
								+ Print_ItemCode + "'";
						selectItemsfStkResvDet = mydb.rawQuery(
								queryItemsfStkResvDet, null);
						if (selectItemsfStkResvDet != null) {
							if (selectItemsfStkResvDet.getCount() > 0) {
								while (selectItemsfStkResvDet.moveToNext()) {
									Print_ResvQty = selectItemsfStkResvDet
											.getString(1);
									if (Print_ResvQty == null) {
										Print_ResvQty = "0.00";
									}
									Log.v(TAG, "Print_ResvQty :" + ""
											+ Print_ResvQty);

								}
								selectItemsfStkResvDet.close();
							} else {
								Print_ResvQty = "0.00";
							}
						} else {
							Print_ResvQty = "0.00";
						}
						/* Select Items Price */
						queryItemsPrice = "SELECT IP.ItemCode,IP.Price,IP.PrilCode FROM fItemPri IP WHERE IP.ItemCode = '"
								+ Print_ItemCode
								+ "' AND IP.PrilCode = '"
								+ Print_PrilCode + "'";
						selectItemsPrice = mydb.rawQuery(queryItemsPrice, null);
						if (selectItemsPrice != null) {
							if (selectItemsPrice.getCount() > 0) {
								while (selectItemsPrice.moveToNext()) {
									Print_ItemPrice = selectItemsPrice
											.getString(1);

									ItemPriceValue = new BigDecimal(
											Print_ItemPrice.replaceAll("[,]",
													""));
									Log.v(TAG, "ItemPriceValue***:" + ""
											+ ItemPriceValue);
									queryItemsfDailyCur = "SELECT FDC.CurCode,FDC.CurDate,FDC.CurRate FROM fDailyCur FDC WHERE FDC.CurCode = 'USD' ORDER BY FDC.CurDate DESC LIMIT 1";
									selectItemsPricefDailyCur = mydb.rawQuery(
											queryItemsfDailyCur, null);
									if (selectItemsPricefDailyCur != null) {
										if (selectItemsPricefDailyCur
												.getCount() > 0) {
											while (selectItemsPricefDailyCur
													.moveToNext()) {
												Print_CurRate = selectItemsPricefDailyCur
														.getString(2);
												ItemCurRate = new BigDecimal(
														Print_CurRate
																.replaceAll(
																		"[,]",
																		""));
												Log.v(TAG, "ItemCurRate :" + ""
														+ ItemCurRate);
												try {
													RationPriceCurRate = ItemPriceValue
															.divide(ItemCurRate,
																	2,
																	RoundingMode.HALF_UP);
													Log.v(TAG,
															"RationPriceCurRate ###:"
																	+ ""
																	+ RationPriceCurRate);
												} catch (Exception e) {
													Log.v(TAG,
															"RationPriceCurRate ###:"
																	+ "" + e);
												}

											}
											selectItemsPricefDailyCur.close();
										} else {
											Print_CurRate = "0.00";
										}
									}

								}
								selectItemsPrice.close();
							} else {
								Print_ItemPrice = "0.00";
							}
						}

						try {
							ContentValues add_inquiry_details = new ContentValues();
							add_inquiry_details.put("ItemCode", Print_ItemCode);
							add_inquiry_details.put("TypeName", Print_TypeName);
							add_inquiry_details.put("ItemName", Print_ItemName);
							add_inquiry_details.put("PurDesc", Print_PurDesc);
							add_inquiry_details.put("BrandName",
									Print_BrandName);
							add_inquiry_details.put("Packing", Print_packing);
							add_inquiry_details.put("FinalQty", Print_FreeQty);
							add_inquiry_details.put("ResvQTY", Print_ResvQty);
							add_inquiry_details
									.put("STDPrice", Print_ItemPrice);
							add_inquiry_details.put("USDPrice", ""
									+ RationPriceCurRate);
							add_inquiry_details.put("UnDispQTY", Print_FreeQty);
							add_inquiry_details.put("PackSize", Print_PackSize);
							add_inquiry_details
									.put("TAXCode", Print_TaxComCode);
							String SummaryValues = Print_ItemCode + " "
									+ Print_ItemName + " " + Print_BrandName;
							add_inquiry_details.put("IQSummary", SummaryValues);

							mydb.insert(ITEMS_INQUIRY, null,
									add_inquiry_details);
						} catch (Exception e) {

						}
						Log.v(TAG, "============************============");
					}

					Log.v(TAG, "#########LOOP END#########");

					selectItems.close();
				} else {
					Log.v(TAG, "Records not excisting");
				}

			}
			mydb.close();
			return null;
		}

		@Override
		protected void onPostExecute(Void args) {

			// new generateReportSummary().execute();

			imgLogo.setVisibility(ImageView.GONE);
			DisplayResults.setVisibility(LinearLayout.VISIBLE);
			DisplayResults();
		}
	}

	private class generateReportSummary extends AsyncTask<Void, Void, Void> {
		private final String TAG = null;
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
		}
		@Override
		protected Void doInBackground(Void... params) {
			// TODO Auto-generated method stub
			return null;
		}
		@Override
		protected void onPostExecute(Void args) {
		}
	}

	@Override
	public void onBackPressed() {
		// Do Here what ever you want do on back press;

	}

	public void DisplayResults() {
		// TODO Auto-generated method stub
		Cursor cursor = dbHelperInquiryReport.fetchAllItemsInquiryOrderBy();
		String[] columns = new String[] {
				DM_BBM_Inquiry_Adapters.KEY_IQ_ITEMCODE,
				DM_BBM_Inquiry_Adapters.KEY_IQ_TYPENAME,
				DM_BBM_Inquiry_Adapters.KEY_IQ_ITEMNAME,
				DM_BBM_Inquiry_Adapters.KEY_IQ_PURDESC,
				DM_BBM_Inquiry_Adapters.KEY_IQ_BRANDNAE,
				DM_BBM_Inquiry_Adapters.KEY_IQ_PACKING,
				DM_BBM_Inquiry_Adapters.KEY_IQ_FINALQTY,
				DM_BBM_Inquiry_Adapters.KEY_IQ_RESVQTY,
				DM_BBM_Inquiry_Adapters.KEY_IQ_STDPRICE,
				DM_BBM_Inquiry_Adapters.KEY_IQ_USDPRICE,
				DM_BBM_Inquiry_Adapters.KEY_IQ_UNDIPQTY,
				DM_BBM_Inquiry_Adapters.KEY_IQ_PACKSIZE,
				DM_BBM_Inquiry_Adapters.KEY_IQ_TAXCODE,
				DM_BBM_Inquiry_Adapters.KEY_IQ_SUMMARY };
		// create the grid item mapping
		String[] fromtrdes = new String[] { "item_result_0", "item_result_1",
				"item_result_2", "item_result_3", "item_result_4",
				"item_result_5", "item_result_6", "item_result_7",
				"item_result_8", "item_result_9", "item_result_10",
				"item_result_11", "item_result_12" };

		int[] to = new int[] { R.id.record_0, R.id.record_1, R.id.record_2,
				R.id.record_3, R.id.record_4, R.id.record_5, R.id.record_6,
				R.id.record_7, R.id.record_8, R.id.record_9, R.id.record_10,
				R.id.record_11, R.id.record_12 };

		dataAdapterItemInquiry = new SimpleCursorAdapter(this,
				R.layout.dm_bbm_items_inquiry_raw, cursor, columns, to, 0);
		ListView listView = (ListView) findViewById(R.id.dmitemsinquirylist);
		// Assign adapter to ListView
		listView.setAdapter(dataAdapterItemInquiry);

		myFilterCustomer.addTextChangedListener(new TextWatcher() {

			public void afterTextChanged(Editable s) {
			}

			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
			}

			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
				dataAdapterItemInquiry.getFilter().filter(s.toString());
			}
		});

		dataAdapterItemInquiry
				.setFilterQueryProvider(new FilterQueryProvider() {
					public Cursor runQuery(CharSequence constraint) {
						return dbHelperInquiryReport
								.fetchAllItemsInquiryBySummary(constraint
										.toString());
					}
				});
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.action_search:
			// search action
			return true;
		case R.id.action_location_found:
			// location found
			LocationFound();
			return true;
		case R.id.action_refresh:
			// refresh
			/*
			 * refreshMenuItem = item; // load the data from server new
			 * SyncData().execute();
			 */
			return true;
		case R.id.action_help:
			// help action
			return true;
		case R.id.action_check_updates:
			// check for updates action
			return true;
		default:
			return super.onOptionsItemSelected(item);
		}
	}

	private void LocationFound() {
		// TODO Auto-generated method stub
		Intent i = new Intent(DM_BBM_Items_Inquiry.this,
				DM_BBM_InvoiceMenu.class);
		i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
				| Intent.FLAG_ACTIVITY_NEW_TASK);
		startActivity(i);
		overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
		finish();
		return;
	}

	@Override
	public boolean onNavigationItemSelected(int itemPosition, long itemId) {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.activity_main_actions, menu);
		return true;
	}

	@Override
	public void onAnimationEnd(Animation animation) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onAnimationRepeat(Animation animation) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onAnimationStart(Animation animation) {
		// TODO Auto-generated method stub

	}

}
